package com.jlnk.stockdemo.utils;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jlnk.stockdemo.callback.ResponseCallback;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class NetworkUtils {
    private static final String TAG = "NetworkUtils";

    public static void sendPostRequest(Object requestBean, ResponseCallback callback) {
        OkHttpClient client = new OkHttpClient();

        // 构建请求体
        Gson gson = new Gson();
        String json = gson.toJson(requestBean);
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");

        // 创建一个请求
        Request request = new Request.Builder()
                .url(Constants.URL)
                .post(RequestBody.create(json, JSON))
                .build();

        // 异步执行请求
        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                // 请求失败时调用
                if (callback != null) {
                    callback.onFailure(e);
                }
            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                // 请求成功时调用
                if (response.isSuccessful() && response.body() != null) {
                    // 获取响应体的字符串
                    String responseData = response.body().string();
                    // 在这里处理响应数据
                    handleResponse(responseData, callback);
                } else if (callback != null) {
                    callback.onFailure(new IOException("Unexpected code " + response));
                }
            }
        });
    }

    private static void handleResponse(String response, ResponseCallback callback) {
        try {
            Log.d(TAG, "NewsViewModel handleResponse: " + response);
            JsonObject jsonResponse = JsonParser.parseString(response).getAsJsonObject();
            int code = jsonResponse.get("code").getAsInt();
            String msg = jsonResponse.get("msg").getAsString();
            JsonObject data = jsonResponse.get("data").getAsJsonObject();

            switch (code) {
                case 2002:
                    callback.onPermissionError(msg);
                    break;
                default:
                    if (callback != null) {
                        callback.onResponse(response);
                    }
                    break;
            }
        } catch (Exception e) {
            if (callback != null) {
                callback.onInternalError("系统内部错误" + e.getMessage());
            }
        }
    }
}